package com.ts.proj.json;


import com.alibaba.fastjson.JSONArray;
import com.ts.base.controller.BaseController;
import com.ts.common.constant.InsUpdDelFlagConstant;
import com.ts.proj.entity.SystemButtonEntity;
import com.ts.proj.entity.SystemMenuEntity;
import com.ts.proj.entity.SystemRoleEntity;
import com.ts.proj.service.SystemButtonService;
import com.ts.proj.service.SystemMenuService;
import com.ts.proj.service.SystemRoleService;
import com.ts.util.JsonUtils;
import com.ts.util.PageData;
import com.ts.util.RightsHelper;
import com.ts.util.TreeMenuUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
public class SystemRoleJson extends BaseController {

    @Autowired
    private SystemRoleService systemRoleService;

    @Autowired
    private SystemMenuService systemMenuService;

    @Autowired
    private SystemButtonService systemButtonService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 后台分页
     * @param start
     * @param length
     * @return
     */
    @RequestMapping("/role-list-json/{start}/{length}")
    public Map<String,Object> roleListJson(@PathVariable("start") Integer start, @PathVariable("length") Integer length){
        PageData pageData = new PageData();
        pageData.put("deleteFlag", InsUpdDelFlagConstant.DELETE_FLAG_N);
        pageData.put("total", systemRoleService.count(pageData));
        pageData.put("rows", systemRoleService.findAll(pageData,start-1,length));
        return pageData;
    }

    /**
     * 初始化权限
     * @param rights
     * @return
     */
    @RequestMapping(value = "/initMenu/{rights}" , produces = "application/json;charset=UTF-8")
    public Map<String,List<PageData>> initMenu(@PathVariable("rights") String rights){
        Map<String,List<PageData>> map = new HashMap<String, List<PageData>>();
        SystemMenuEntity systemMenuEntity = new SystemMenuEntity();
        systemMenuEntity.setId(0);
        systemMenuEntity.setParentId("0");
        List<SystemMenuEntity> allMenu = systemMenuService.findAll();
        List<PageData> result = new ArrayList<PageData>();
        result = new TreeMenuUtil().getTreeMenu(allMenu,systemMenuService);
        List<PageData> nodes = new ArrayList<PageData>();
        for(PageData tPageData : result ){
            if(tPageData.getString("PARENT_ID").equals("0")){
                int mu = Integer.valueOf(tPageData.get("MENU_ID").toString());
                PageData parentPD = new PageData();
                parentPD.put("id",mu);
                parentPD.put("pId",tPageData.getString("PARENT_ID"));
                parentPD.put("name",tPageData.getString("MENU_NAME"));
                parentPD.put("checked", RightsHelper.testRights(rights.substring(1),mu));
                nodes.add(parentPD);
                List<SystemMenuEntity> firstSubMenu = (List<SystemMenuEntity>) tPageData.get("firstSubMenu");
                for(SystemMenuEntity subPageData : firstSubMenu){
                    int smu = subPageData.getId();
                    PageData firstPD = new PageData();
                    firstPD.put("id",smu);
                    firstPD.put("pId",subPageData.getParentId());
                    firstPD.put("name",subPageData.getMenuName());
                    firstPD.put("checked", RightsHelper.testRights(rights.substring(1),smu));
                    nodes.add(firstPD);
                }
            }
        }
        map.put("nodes",nodes);
        return map;
    }

    /**
     * 一统江湖
     *
     */
    @RequestMapping("/role-assign-json/{mRights}/{bRights}")
    public Object roleAssignJsonString(@PathVariable("mRights") String mRights,@PathVariable("bRights") String bRights){
        List<PageData> firstPdList = new ArrayList<>();
        PageData firstPd = new PageData();
        firstPd.put("parentId", 0);
        firstPd.put("deleteFlag", InsUpdDelFlagConstant.DELETE_FLAG_N);
        List<SystemMenuEntity> firstSystemMenuList = systemMenuService.findAll(firstPd);
        String mRightsStr = mRights.substring(1);
        String bRightsStr = bRights.substring(1);
        for(SystemMenuEntity firstMenuEntity :firstSystemMenuList){
            PageData firstEntity = new PageData();
            PageData secondPd = new PageData();
            List<PageData> secondPageDataList = new ArrayList<>();
            secondPd.put("parentId", firstMenuEntity.getId());
            secondPd.put("deleteFlag", InsUpdDelFlagConstant.DELETE_FLAG_N);
            List<SystemMenuEntity> secondSystemMenuList = systemMenuService.findAll(secondPd);
            firstEntity.put("id", "M"+firstMenuEntity.getId());
            firstEntity.put("text", firstMenuEntity.getMenuName());
            if(RightsHelper.testRights(mRightsStr,firstMenuEntity.getId())){
                firstEntity.put("checked", true);
            }
            for(SystemMenuEntity secondMenuEntity:secondSystemMenuList){
                PageData secondEntity = new PageData();
                secondEntity.put("id","M"+secondMenuEntity.getId());
                secondEntity.put("text", secondMenuEntity.getMenuName());
                if(RightsHelper.testRights(mRightsStr,secondMenuEntity.getId())){
                    secondEntity.put("checked", true);
                }
                PageData buttonPd = new PageData();
                buttonPd.put("deleteFlag", InsUpdDelFlagConstant.DELETE_FLAG_N);
                buttonPd.put("menuID", secondMenuEntity.getId());
                List<SystemButtonEntity> thirdSystemButtonEntity = systemButtonService.findAll(buttonPd);
                List<PageData> thirdPageDataList = new ArrayList<>();
                for(SystemButtonEntity buttonEntity : thirdSystemButtonEntity){
                    PageData thirdEntity = new PageData();
                    thirdEntity.put("id", "B"+buttonEntity.getId());
                    log.info(buttonEntity.getId()+"");
                    if(RightsHelper.testRights(bRightsStr,buttonEntity.getId())){
                        thirdEntity.put("checked", true);
                    }
                    thirdEntity.put("text", buttonEntity.getButtonName());
                    thirdEntity.put("iconCls", buttonEntity.getIconCls());
                    thirdPageDataList.add(thirdEntity);
                }
                if(thirdPageDataList.size()!=0){
                    secondEntity.put("children", thirdPageDataList);
                    secondEntity.put("state", "closed");
                }
                secondPageDataList.add(secondEntity);
            }
            if(secondPageDataList.size()!=0){
                firstEntity.put("children", secondPageDataList);
                firstEntity.put("state", "closed");
            }
            firstPdList.add(firstEntity);
        }
        Object obj = JSONArray.parseArray(JsonUtils.objectToJson(firstPdList));
        return obj;
    }


    /**
     * 一统江湖
     * @param id
     * @return
     */
    @RequestMapping("/role-assign/{id}")
    public String roleAssignSave(@PathVariable("id") String id){
        PageData pd = this.getPageData();
        String ids = pd.getString("ids");
        log.info(ids);
        String[] split = ids.split(",");
        List<String> menuIds = new ArrayList<>();
        List<String> buttonIds = new ArrayList<>();
        for(int i=0;i<split.length;i++){
            String str = split[i];
            //先判断父,P表示菜单一二级
            if(str.startsWith("M")){
                menuIds.add(str.substring(1));
            }else if(str.startsWith("B")){
                buttonIds.add(str.substring(1));
            }
        }
        String menuArray[] = new String[menuIds.size()];
        String buttonArray[] = new String[buttonIds.size()];
        String rights = "R"+String.valueOf(RightsHelper.sumRights(menuIds.toArray(menuArray)));
        String buttonRights = "B" + String.valueOf(RightsHelper.sumRights(buttonIds.toArray(buttonArray)));

        SystemRoleEntity systemRoleEntity = systemRoleService.findById(Integer.valueOf(id));
        if(systemRoleEntity!=null){
            systemRoleEntity.setRights(rights);
            systemRoleEntity.setBtnRights(buttonRights);
            systemRoleService.save(systemRoleEntity);
        }

        return "success";
    }

    @RequestMapping("/role-ins-upd-del/{id}")
    public String roleInsUpdDel(@PathVariable("id") String id){
        PageData pageData = this.getPageData();
        SystemRoleEntity roleEntity = systemRoleService.findById(Integer.valueOf(id));
        if(null!=pageData.get("roleName")&&!"".equals(pageData.getString("roleName"))){
            roleEntity.setRoleName(pageData.getString("roleName"));
        }
        if(null!=pageData.get("rights")&&!"".equals(pageData.getString("rights"))){
            roleEntity.setRights(pageData.getString("rights"));
        }
        if(null!=pageData.get("btnRights")&&!"".equals(pageData.getString("btnRights"))){
            roleEntity.setBtnRights(pageData.getString("btnRights"));
        }
        if(null!=pageData.get("deleteFlag")&&!"".equals(pageData.getString("deleteFlag"))){
            roleEntity.setDeleteFlag(InsUpdDelFlagConstant.DELETE_FLAG_Y);
        }

        try{
            stringRedisTemplate.delete("role");
        }catch (Exception e){

        }
        systemRoleService.save(roleEntity);
        return "";
    }


    @RequestMapping("/role-list")
    public Object adminGetRoleList(){
        List<PageData> pageDataList = new ArrayList<PageData>();
        PageData tempPa = new PageData();
        tempPa.put("deleteFlag", InsUpdDelFlagConstant.DELETE_FLAG_N);
        List<SystemRoleEntity> roleEntities = systemRoleService.findAll(tempPa);
        for(SystemRoleEntity roleEntity : roleEntities){
            PageData pd = new PageData();
            pd.put("value",roleEntity.getId());
            pd.put("text",roleEntity.getRoleName());
            pageDataList.add(pd);
        }
        return JSONArray.toJSONString(pageDataList);
    }

    @RequestMapping("/role-id2name/{roleId}")
    public String adiminRoleId2RoleName(@PathVariable("roleId") Integer roleId){
//        PageData pageData = new PageData();
//        pageData.put("id", roleId);
        List<Integer> ids = new ArrayList<>();
        for(int i=0;i<500;i++){
            if(RightsHelper.testRights(String.valueOf(roleId), i)){
                ids.add(i);
            }
        }
        List<SystemRoleEntity> roleEntities = systemRoleService.getSystemRoleEntityListByIds(ids);
        if(0==roleEntities.size()){
            return "";
        }else{
            String str = "";
            for(SystemRoleEntity entity : roleEntities){
                if(!str.equals("")){
                    str += "|";
                }
                str += entity.getRoleName();
            }
            return str;
        }
    }
}
